﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using EIS.Obj;
using EIS.ServerAdapter;
using EIS.ClientUtility;

namespace EIS.ViewFactory
{
    public class ViewFactory
    {
        public UserControl GetView(string functionID)
        {
            string url = GlobalVariable.Instance.ServerRootURL;

            url = url + @"functionDestInvokeInfo/" + functionID + @"/" + GlobalVariable.Instance.CurrentToken;

            DataSet dsInvokeInfo = RestAdapter.HttpGet(url);
            if (dsInvokeInfo.Tables.Count == 0) return null;
            if (dsInvokeInfo.Tables[0].TableName.ToUpper() == "ERROR")
            {
                throw new Exception(dsInvokeInfo.Tables[0].Rows[0]["errorCode"].ToString() + dsInvokeInfo.Tables[0].Rows[0]["errorMessage"].ToString());
                return null;
            }

            
            if (dsInvokeInfo.Tables.Count == 0)
            {
                return null;
            }

            var dr = dsInvokeInfo.Tables[0].Rows[0];
            string strBaseDir = AppDomain.CurrentDomain.BaseDirectory;
            string strPathToAsm = Path.Combine(strBaseDir, dr["clientLibraryFileName"].ToString());

            Assembly objAsm = Assembly.LoadFile(strPathToAsm);
            Type type = objAsm.GetType(dr["clientClassName"].ToString());

            object[] args = new object[] {functionID};
            object objTemp = Activator.CreateInstance(type, args);

            var objUserControl = objTemp as System.Windows.Forms.UserControl;

            return objUserControl;

        }
    }
}
